package com.billdowney.qq.robot.plugins.provide.baidu.yiyan;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.billdowney.qq.robot.annotations.HookMethod;
import com.billdowney.qq.robot.annotations.HookNotice;
import com.billdowney.qq.robot.bean.ConfigBean;
import com.billdowney.qq.robot.plugins.RobotPlugin;
import com.billdowney.qq.robot.plugins.RobotPluginContent;
import com.billdowney.qq.robot.plugins.provide.baidu.access.AccessTokenService;
import com.billdowney.qq.robot.util.MessageUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.message.data.QuoteReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 接入文心一言
 * <a href="https://yiyan.baidu.com/developer/doc">文心一言</a>
 * <a href="https://cloud.baidu.com/doc/WENXINWORKSHOP/s/4lilb2lpf">开发者平台</a>
 *
 * @author BillDowney
 */
@Component
@Slf4j
@HookNotice(name = "文心一言插件", start = true)
public class YiyanRobotPlugin implements RobotPlugin {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ConfigBean configBean;
    @Autowired
    private AccessTokenService accessTokenService;

    @HookMethod(start = "文心一言")
    public void yiyan(RobotPluginContent content) {
        MessageChainBuilder builder = MessageUtil.createBuilder();
        builder.add(new QuoteReply(content.getMessageEvent().getMessage()));
        if (StrUtil.isBlank(content.getFilterContent())) {
            builder.add("不说话，是想干嘛~");
        } else {
            YiyanRequestBody body = new YiyanRequestBody();
            body.addUserMessage(content.getFilterContent());
            try {
                YiyanResponse yiyanResponse = this.sendRequest(body);
                if (yiyanResponse.success()) {
                    builder.add(yiyanResponse.getResult());
                } else {
                    builder.add(yiyanResponse.getErrorCode() + ":" + yiyanResponse.getErrorMsg());
                }
            } catch (JsonProcessingException e) {
                builder.add("出错了：" + e.getMessage());
                log.error("出错了", e);
            }
        }
        content.putReplyMessage(builder);
    }

    public YiyanResponse sendRequest(YiyanRequestBody body) throws JsonProcessingException {
        return this.objectMapper.readValue(HttpUtil.post(this.getUrl(), objectMapper.writeValueAsString(body)), YiyanResponse.class);
    }

    private String getUrl() {
        return this.configBean.getBaidu().getYiyanUrl() + "?access_token=" + this.accessTokenService.getAccessToken();
    }

}
